from flask import Blueprint, jsonify, request, current_app
from models import Product, db
from sqlalchemy import desc, func

api_bp = Blueprint('product', __name__)


# 1. 获取商品列表（支持分页、搜索、排序）
@api_bp.route('/products', methods=['GET'])
def get_products():
    try:
        # 分页参数
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        page_size = min(max(page_size, 1), 100)  # 限制每页最大100条

        # 搜索参数
        keyword = request.args.get('keyword', '').strip()

        # 排序参数（支持按价格/时间排序）
        sort_by = request.args.get('sort_by', 'created_at')
        order = request.args.get('order', 'desc')

        # 构建查询
        query = Product.query

        # 关键词搜索（商品名称模糊匹配）
        if keyword:
            query = query.filter(Product.name.like(f'%{keyword}%'))

        # 排序规则
        if sort_by == 'price':
            order_clause = desc(Product.price) if order == 'desc' else Product.price
        else:  # 默认按创建时间排序
            order_clause = desc(Product.created_at) if order == 'desc' else Product.created_at
        query = query.order_by(order_clause)

        # 分页计算
        total_items = query.count()
        total_pages = (total_items + page_size - 1) // page_size
        page = max(1, min(page, total_pages))  # 防止页码越界

        # 执行分页查询
        products = query.offset((page - 1) * page_size).limit(page_size).all()

        # 格式化数据
        data = []
        for product in products:
            data.append({
                "id": product.id,
                "name": product.name,
                "price": float(product.price),
                "image": product.image or "/static/default-product.jpg",  # 兜底默认图
                "created_at": product.created_at.strftime("%Y-%m-%d %H:%M:%S")
            })

        return jsonify({
            "message": "获取商品列表成功",
            "data": data,
            "pagination": {
                "current_page": page,
                "page_size": page_size,
                "total_pages": total_pages,
                "total_items": total_items
            }
        }), 200

    except Exception as e:
        current_app.logger.error(f"获取商品列表失败: {str(e)}", exc_info=True)
        return jsonify({"message": "获取商品列表失败"}), 500


# 2. 获取推荐商品（随机返回10个商品）
@api_bp.route('/products/recommend', methods=['GET'])
def get_recommend_products():
    try:
        # 注意：对于数据量大的表，此方法性能可能不佳，可改用缓存或其他优化方案
        recommend_products = Product.query.order_by(func.random()).limit(40).all()

        if not recommend_products:
            return jsonify({"message": "暂无推荐商品"}), 404

        data = []
        for product in recommend_products:
            data.append({
                "id": product.id,
                "name": product.name,
                "price": float(product.price),
                "image": product.image or "/static/default-product.jpg",
                "created_at": product.created_at.strftime("%Y-%m-%d %H:%M:%S")
            })

        return jsonify({
            "message": "获取推荐商品成功",
            "data": data
        }), 200

    except Exception as e:
        current_app.logger.error(f"获取推荐商品失败: {str(e)}", exc_info=True)
        return jsonify({"message": "获取推荐商品失败"}), 500


# 3. 获取热门商品（随机返回10个商品）
@api_bp.route('/products/hot', methods=['GET'])
def get_hot_products():
    try:
        # 随机获取40个商品（实际业务中应按销量/评分等排序）
        hot_products = Product.query.order_by(func.random()).limit(40).all()

        if not hot_products:
            return jsonify({"message": "暂无热门商品"}), 404

        data = []
        for product in hot_products:
            data.append({
                "id": product.id,
                "name": product.name,
                "price": float(product.price),
                "image": product.image or "/static/default-product.jpg"
            })

        return jsonify({
            "message": "获取热门商品成功",
            "data": data
        }), 200

    except Exception as e:
        current_app.logger.error(f"获取热门商品失败: {str(e)}", exc_info=True)
        return jsonify({"message": "获取热门商品失败"}), 500